package com.hopes.bizz.risk.transfer.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.hopes.bizz.risk.transfer.bean.bo.RiskTransferResult;
import com.hopes.bizz.risk.transfer.constant.RiskConstant;
import com.hopes.bizz.risk.transfer.constant.RiskStatusCode;
import com.hopes.bizz.risk.transfer.bean.entity.RiskTransferAuthEntity;
import com.hopes.bizz.risk.transfer.helper.RiskAuthorizationValidation;
import com.hopes.bizz.risk.transfer.service.RiskTransferAuthService;
import lombok.Cleanup;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @author lyb
 * @version 1.0
 * @description: 数据交换认证拦截器
 * @date 2024/1/31 16:34
 */
@Slf4j
@Component
public class RiskAuthInterceptor implements HandlerInterceptor {


    @Lazy
    @Resource
    private RiskTransferAuthService riskTransferAuthService;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object object) {
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        // 获取token
        String authorization = request.getHeader(RiskConstant.HEADER_AUTHORIZATION);
        RiskAuthorizationValidation validation = new RiskAuthorizationValidation(authorization);
        // 校验token格式
        if (!validation.checkFormat()) {
            writerData(response, RiskStatusCode.HTTP_TOKEN_ANALYZE_ERROR);
            return false;
        }
        // 校验token有效期
        if (!validation.checkExpired()) {
            writerData(response, RiskStatusCode.HTTP_TOKEN_EXPIRED);
            return false;
        }
        // 校验请求大小
        int size = request.getContentLength();
        if (size == 0) {
            log.info("请求数据内容为空");
            writerData(response, RiskStatusCode.HTTP_CONTENT_ERROR);
            return false;
        }
        if (size > RiskConstant.REQUEST_SIZE_LIMIT) {
            log.info("请求数据过大,字节数:{}", size);
            writerData(response, RiskStatusCode.HTTP_SIZE_ERROR);
            return false;
        }
        // 校验数据权限
        RiskTransferAuthEntity riskTransferAuth = riskTransferAuthService.lambdaQuery()
                .eq(RiskTransferAuthEntity::getUse, true)
                .eq(RiskTransferAuthEntity::getToken, validation.getToken())
                .select(RiskTransferAuthEntity::getOrgId)
                .one();
        if (Objects.isNull(riskTransferAuth)) {
            writerData(response, RiskStatusCode.HTTP_TOKEN_INVALID);
        }
        RiskCompanyHolder.setCompanyId(riskTransferAuth.getOrgId());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RiskCompanyHolder.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    @SneakyThrows
    private void writerData(HttpServletResponse response, RiskStatusCode riskStatusCode) {
        response.setContentType("application/json;charset=UTF-8");
        @Cleanup
        PrintWriter writer = response.getWriter();
        writer.print(JSON.toJSONString(new RiskTransferResult(riskStatusCode), SerializerFeature.WriteMapNullValue));

    }
}
